package other;

import sf.tools.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DownloadImg {
    public static void main(String[] args) {
        List<String> urls = new ArrayList<String>();


        urls.add("https://www.xx.jpg");
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("fileName", "");
        map.put("urls", urls);
        DownloadImg img = new DownloadImg();
        img.download(map);
    }

    public void download(Map<String, Object> map) {

        List<String> urls = (List<String>) map.get("urls");
        String fileName = (String) map.get("fileName");
        for (String imgUrl : urls) {
            if (StringUtils.isEmpty(imgUrl)) {
                continue;
            }
            System.out.println(imgUrl);
            System.out.println();
            try {
                String filename = imgUrl.substring(imgUrl.lastIndexOf("/"));
                String savePath = "D://壁纸/";
                // 构造URL
                URL url = new URL(imgUrl);
                // 打开连接
                URLConnection con = url.openConnection();
                con.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
                //设置请求超时为5s
                con.setConnectTimeout(5 * 1000);
                // 输入流
                InputStream is = con.getInputStream();
                // 1K的数据缓冲
                byte[] bs = new byte[1024];
                // 读取到的数据长度
                int len;
                // 输出的文件流
                File sf = new File(savePath);
                if (!sf.exists()) {
                    sf.mkdirs();
                }
                long length = (sf.length()) / 128;
                OutputStream os = new FileOutputStream(sf.getPath() + "/" + filename);
                // 开始读取
                while ((len = is.read(bs)) != -1) {
                    os.write(bs, 0, len);
                }
                // 完毕，关闭所有链接
                os.close();
                is.close();

            } catch (Exception e) {
                e.printStackTrace();
                //urls.add(imgUrl);
                continue;
            }
        }

        System.out.println("===================end====================");
    }

    private static byte[] readInputStream(InputStream inputStream) throws IOException {

        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
}